package com.xzx.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/11/5 15:49
 */
@Slf4j
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("[客户端] - {} 连接成功", ctx.channel().remoteAddress());
        ctx.writeAndFlush(new TextWebSocketFrame("连接成功"));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("[客户端] - {} 发送的消息:{}", ctx.channel().remoteAddress(), msg.text());
        ctx.writeAndFlush(new TextWebSocketFrame("[服务端] - " + msg.text()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("exceptionCaught channel:{}", ctx.channel().remoteAddress(), cause);
        ctx.close();
    }
}
